import fetch from 'node-fetch';
import puppeteer from '../../lib/puppeteer/puppeteer.js'
import fs from 'fs';

export class EpicFreeGame extends plugin {
    constructor() {
        super({
            name: 'Epic免费游戏',
            dsc: '获取Epic免费游戏信息',
            event: 'message',
            priority: 50,
            rule: [
                {
                    reg: '^#?(epic|Epic|EPIC|喜加一)$',
                    fnc: 'getEpicFreeGameInfo'
                }
            ]
        });
    }

    async getEpicFreeGameInfo() {
        if (!fs.existsSync('resources/html/Epic免费游戏.html')) {
            fs.mkdirSync('resources/html', { recursive: true });
            const html = await (await fetch('https://gitee.com/Tloml-Starry/resources/raw/master/resources/html/Epic%E5%85%8D%E8%B4%B9%E6%B8%B8%E6%88%8F.html')).text();
            fs.writeFileSync('resources/html/Epic免费游戏.html', html);
        }
        const FreeGameInfo = await displayGames();

        let html = '';
        for (const game of FreeGameInfo) {
            html += `<div class="game-card">`
            if (game.label.Gs) {
                html += `<div class="game-label" style="color: green;">${game.label.message}</div>`
            } else if (game.label.Gs === false) {
                html += `<div class="game-label" style="color: orange;">${game.label.message}</div>`
            }
            html += `<img src="${game.img}" alt="${game.title}">`
            html += `<div class="game-title">${game.title}</div>`
            html += `<div class="game-description">${game.description}</div>`
            html += `<div class="game-price"><span class="original-price">${game.originalPrice}</span> <span class="discount-price">${game.discountPrice}</span></div>`
            html += `</div>`
        }

        const inventoryImage = await puppeteer.screenshot('Epic免费游戏', {
            tplFile: 'resources/html/Epic免费游戏.html',
            html
        })

        this.reply(inventoryImage);
    }
}

async function fetchGames() {
    try {
        const response = await fetch('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=zh-CN&country=CN&allowCountries=CN');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        return data.data.Catalog.searchStore.elements;
    } catch (error) {
        console.error('获取游戏数据时出错:', error);
        return [];
    }
}

function createGameCard(game) {
    const now = new Date();
    let label = '';

    if (game.promotions && game.promotions.promotionalOffers.length > 0) {
        const promo = game.promotions.promotionalOffers[0].promotionalOffers[0];
        const startDate = new Date(promo.startDate);
        const endDate = new Date(promo.endDate);
        if (now >= startDate && now <= endDate) {
            label = { message: `现在免费，结束日期: ${endDate.toLocaleDateString()}`, Gs: true };
        }
    } else if (game.promotions && game.promotions.upcomingPromotionalOffers.length > 0) {
        const upcomingPromo = game.promotions.upcomingPromotionalOffers[0].promotionalOffers[0];
        const upcomingStartDate = new Date(upcomingPromo.startDate);
        const upcomingEndDate = new Date(upcomingPromo.endDate);
        if (now < upcomingStartDate) {
            label = { message: `即将推出，开始: ${upcomingStartDate.toLocaleDateString()} ~ 结束: ${upcomingEndDate.toLocaleDateString()}`, Gs: false };
        }
    }

    return {
        title: game.title,
        img: game.keyImages[0].url,
        description: game.description,
        originalPrice: game.price.totalPrice.fmtPrice.originalPrice,
        discountPrice: game.price.totalPrice.fmtPrice.discountPrice,
        label: label
    };
}

async function displayGames() {
    const games = await fetchGames();

    if (games.length === 0) {
        console.log('无法获取游戏数据，请稍后再试。');
        return;
    }

    const filteredGames = games.filter(game => game.promotions !== null);
    filteredGames.sort((a, b) => a.price.totalPrice.discountPrice - b.price.totalPrice.discountPrice);

    let gameCards = [];
    filteredGames.forEach(game => {
        const gameCard = createGameCard(game);
        gameCards.push(gameCard);
    });

    return gameCards;
}